package com.javer.core;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 敏感词定时任务
 */
public class SensWordJobBean implements InitializingBean {
	private final Log logger = LogFactory.getLog(getClass());
	private JdbcTemplate jdbcTemplate;
	private TransactionTemplate txTemplate;
	
	private TransactionCallback txCallBack = new TransactionCallback() {
		
		public Object doInTransaction(TransactionStatus status) {
			try {
				doJob();
			} catch (Exception e) {
				logger.error("定时任务执行发生异常：", e);
			}
			return null;
		}
	};

	public void doIt() {
		logger.info("敏感词处理定时任务启动");
		long start = System.currentTimeMillis();
		try {
			txTemplate.execute(txCallBack);
		}
		finally {
			logger.info("敏感词处理定时任务执行完成，执行时间为：" + (System.currentTimeMillis() - start) + "ms");
		}
	}
	
	public void doJob() {
		jdbcTemplate.execute(new ConnectionCallback() {
			
			public void replaceByKey(ResultSet rs, Iterator<Entry<String, String>> iter) throws SQLException {
				String content = rs.getString(2);
				while (iter.hasNext()) {
					Entry<String, String> entry = iter.next();
					if (content.indexOf(entry.getKey()) >= 0) {
						content = content.replaceAll(entry.getKey(), entry.getValue());
						rs.updateString(2, content);
						rs.updateRow();
						logger.info("发现敏感词并替换(*)：" + entry.getKey());
					}
				}
			}

			public Object doInConnection(Connection con) throws SQLException,
					DataAccessException {
				con.setAutoCommit(false);
				Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT);
				ResultSet rs = stmt.executeQuery("select id, content from comment");
				
				for (int i = 1; rs.next(); i++) {
					replaceByKey(rs, SensWordCache.iterateLow());
					replaceByKey(rs, SensWordCache.iterateMedium());
					replaceByKey(rs, SensWordCache.iterateHigh());
					
					if (i % 100 == 0) {
						con.commit(); // 提交部分数据
						logger.info("定时任务事务阶段提交成功！");
					}
				}
				rs.close();
				stmt.close();
				return null;
			}
		});
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
		txTemplate = new TransactionTemplate();
	}
	
	public void setTransactionManager(DataSourceTransactionManager transactionManager) {
		txTemplate = new TransactionTemplate();
		txTemplate.setTransactionManager(transactionManager);
	}

	public void afterPropertiesSet() throws Exception {
		logger.info("敏感词处理定时任务初始化成功");
	}
	
}
